<template>
  <view class="page-container">
    <!-- 固定头部 -->
    <view class="header-fixed">
      <S1Header title="打印配置" :on-back="goBack" />
    </view>

    <view class="content-wrapper">
      <view class="form-list">
        <!-- 默认打印份数 -->
        <view class="form-item">
          <text class="item-label">
            默认打印份数
          </text>
          <u-number-box
            v-model="formData.count"
            :min="1"
            :max="999"
            :step="1"
            @change="onCountChange"
          />
        </view>

        <!-- 结账自动打印 -->
        <view class="form-item">
          <text class="item-label">
            结账自动打印
          </text>
          <switch
            :checked="formData.isAoto === 1"
            color="#4ca75b"
            @change="onAutoPrintChange"
          />
        </view>

        <!-- 开单打印模式 -->
        <view class="form-item column">
          <text class="item-label">
            开单打印模式
          </text>
          <radio-group class="radio-group" @change="onPrintModeChange">
            <label class="radio-label">
              <radio
                :value="1"
                :checked="formData.print_huozhu_chaifen === 1"
                color="#4ca75b"
              />
              <text class="radio-text">不拆分</text>
            </label>
            <label class="radio-label">
              <radio
                :value="2"
                :checked="formData.print_huozhu_chaifen === 2"
                color="#4ca75b"
              />
              <text class="radio-text">货主拆分打印</text>
            </label>
            <label class="radio-label">
              <radio
                :value="3"
                :checked="formData.print_huozhu_chaifen === 3"
                color="#4ca75b"
              />
              <text class="radio-text">按单品拆分</text>
            </label>
          </radio-group>
        </view>

        <!-- 分拣单打印模式 -->
        <view class="form-item column">
          <text class="item-label">
            分拣单打印模式
          </text>
          <radio-group class="radio-group" @change="onSortModeChange">
            <label class="radio-label">
              <radio
                :value="0"
                :checked="formData.print_fenjian === 0"
                color="#4ca75b"
              />
              <text class="radio-text">A4</text>
            </label>
            <label class="radio-label">
              <radio
                :value="1"
                :checked="formData.print_fenjian === 1"
                color="#4ca75b"
              />
              <text class="radio-text">小票</text>
            </label>
          </radio-group>
        </view>

        <!-- 小票打印样式 -->
        <view class="form-item column">
          <text class="item-label">
            小票打印样式
          </text>
          <radio-group class="radio-group" @change="onTemplateChange">
            <label class="radio-label">
              <radio
                :value="1"
                :checked="formData.use_print_template === 1"
                color="#4ca75b"
              />
              <text class="radio-text">文本样式</text>
            </label>
            <label class="radio-label">
              <radio
                :value="2"
                :checked="formData.use_print_template === 2"
                color="#4ca75b"
              />
              <text class="radio-text">多行文本样式</text>
            </label>
            <label class="radio-label">
              <radio
                :value="3"
                :checked="formData.use_print_template === 3"
                color="#4ca75b"
              />
              <text class="radio-text">竖向表格样式</text>
            </label>
            <label class="radio-label">
              <radio
                :value="4"
                :checked="formData.use_print_template === 4"
                color="#4ca75b"
              />
              <text class="radio-text">横向表格样式</text>
            </label>
          </radio-group>
        </view>

        <!-- 选择打印内容 -->
        <view class="form-item column print-content-section">
          <text class="item-label">
            选择打印内容
          </text>

          <!-- 头部信息 -->
          <view class="content-group">
            <view class="group-title-wrapper">
              <text class="group-title">
                {{ header.mark }}
              </text>
            </view>
            <view class="checkbox-wrapper">
              <view
                v-for="(item, index) in header.boxList"
                :key="index"
                class="checkbox-label"
                @click="toggleCheck('header', index)"
              >
                <checkbox
                  :value="item.field_name"
                  :checked="item.checked"
                  color="#4ca75b"
                />
                <text class="checkbox-text" :class="{ checked: item.checked }">
                  {{ item.flield_name }}
                </text>
              </view>
            </view>
          </view>

          <!-- 商品信息 -->
          <view class="content-group">
            <view class="group-title-wrapper">
              <text class="group-title">
                {{ goods.mark }}
              </text>
            </view>
            <view class="checkbox-wrapper">
              <view
                v-for="(item, index) in goods.boxList"
                :key="index"
                class="checkbox-label"
                @click="toggleCheck('goods', index)"
              >
                <checkbox
                  :value="item.field_name"
                  :checked="item.checked"
                  color="#4ca75b"
                />
                <text class="checkbox-text" :class="{ checked: item.checked }">
                  {{ item.flield_name }}
                </text>
              </view>
            </view>
          </view>

          <!-- 结算信息 -->
          <view class="content-group">
            <view class="group-title-wrapper">
              <text class="group-title">
                {{ settle.mark }}
              </text>
            </view>
            <view class="checkbox-wrapper">
              <view
                v-for="(item, index) in settle.boxList"
                :key="index"
                class="checkbox-label"
                @click="toggleCheck('settle', index)"
              >
                <checkbox
                  :value="item.field_name"
                  :checked="item.checked"
                  color="#4ca75b"
                />
                <text class="checkbox-text" :class="{ checked: item.checked }">
                  {{ item.flield_name }}
                </text>
              </view>
            </view>
          </view>

          <!-- 其他信息 -->
          <view class="content-group">
            <view class="group-title-wrapper">
              <text class="group-title">
                {{ other.mark }}
              </text>
            </view>
            <view class="checkbox-wrapper">
              <view
                v-for="(item, index) in other.boxList"
                :key="index"
                class="checkbox-label"
                @click="toggleCheck('other', index)"
              >
                <checkbox
                  :value="item.field_name"
                  :checked="item.checked"
                  color="#4ca75b"
                />
                <text class="checkbox-text" :class="{ checked: item.checked }">
                  {{ item.flield_name }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 打印预览组件 - 固定在底部 -->
    <view class="print-preview-fixed">
      <PrintPreview
        :template-type="formData.use_print_template"
        :print-details="printDetails"
        :userinfo="userinfo"
      />
    </view>

    <!-- 打印机选择对话框 -->
    <view
      v-if="selectPrinterShow"
      class="printer-modal"
      @click.self="selectPrinterShow = false"
    >
      <view class="printer-modal-content">
        <view class="printer-modal-header">
          <text class="header-title">
            打印机列表
          </text>
          <view class="header-actions">
            <button class="add-feie-btn" size="mini" @click="addFeiyePrinter">
              添加飞蛾打印机
            </button>
            <text class="close-icon" @click="selectPrinterShow = false">
              ✕
            </text>
          </view>
        </view>

        <!-- Loading -->
        <view v-if="searchLoading" class="loading-mask">
          <view class="loading-content">
            <view class="loading-icon" />
            <text>{{ elementLoadingText }}</text>
          </view>
        </view>

        <scroll-view class="printer-list" scroll-y>
          <!-- 空状态提示 -->
          <view
            v-if="
              usbDevice.length === 0
                && blueDevice.length === 0
                && printerList.length === 0
            "
            class="empty-tip"
          >
            <text>暂无打印机设备</text>
            <text class="sub-tip">
              点击底部“搜索”按钮搜索蓝牙设备
            </text>
          </view>

          <!-- USB 打印机 -->
          <view
            v-for="(item, index) in usbDevice"
            :key="`usb-${index}`"
            class="printer-item"
          >
            <view class="printer-info">
              <view class="info-row">
                <text class="label">
                  打印机名称：
                </text>
                <text class="value">
                  {{ item.deviceName }}
                </text>
              </view>
              <view class="info-row">
                <text class="label">
                  打印机Id：
                </text>
                <text class="value">
                  {{ item.deviceId }}
                </text>
              </view>
              <text class="printer-note">
                备注
                <text class="note-text">
                  这是USB打印机
                </text>
              </text>
            </view>
            <view class="printer-actions">
              <button
                v-if="connectDeviceId === item.id"
                type="warn"
                size="mini"
                @click="disconnectPrint"
              >
                断开连接
              </button>
              <button v-else type="primary" size="mini" @click="selectlyPrint(item, 1)">
                连接
              </button>
            </view>
          </view>

          <!-- 蓝牙打印机 -->
          <view
            v-for="(item, index) in blueDevice"
            :key="`blue-${index}`"
            class="printer-item"
          >
            <view class="printer-info">
              <view class="info-row">
                <text class="label">
                  蓝牙名称：
                </text>
                <text class="value">
                  {{ item.name }}
                </text>
              </view>
              <view class="info-row">
                <text class="label">
                  蓝牙地址：
                </text>
                <text class="value">
                  {{ item.address }}
                </text>
              </view>
              <text class="printer-note">
                备注
                <text class="note-text">
                  这是蓝牙打印机
                </text>
              </text>
            </view>
            <view class="printer-actions">
              <button
                v-if="connectDeviceId === item.address"
                type="warn"
                size="mini"
                @click="disconnectPrint"
              >
                断开连接
              </button>
              <button v-else type="primary" size="mini" @click="selectlyPrint(item, 2)">
                连接
              </button>
            </view>
          </view>

          <!-- 飞蛾打印机 -->
          <view
            v-for="(item, index) in printerList"
            :key="`feie-${index}`"
            class="printer-item"
          >
            <view class="printer-info" @click="selectFeiyePrint(item)">
              <view class="info-row">
                <text class="value bold">
                  {{ item.name }}
                </text>
              </view>
              <view class="info-row">
                <text class="label">
                  设备编号：
                </text>
                <text class="value">
                  {{ item.num }}
                </text>
              </view>
              <view class="info-row">
                <text class="label">
                  设备Key：
                </text>
                <text class="value">
                  {{ item.key }}
                </text>
              </view>
              <view v-if="item.note" class="info-row">
                <text class="printer-note">
                  备注
                  <text class="note-text">
                    {{ item.note }}
                  </text>
                </text>
              </view>
            </view>
            <view class="printer-actions">
              <view class="action-btn edit-btn" @click.stop="editFeiyePrinter(item)">
                <view class="icon-edit" />
              </view>
              <view class="action-btn delete-btn" @click.stop="deleteFeiyePrinter(item.id)">
                <view class="icon-delete" />
              </view>
            </view>
          </view>
        </scroll-view>

        <!-- 搜索按钮 -->
        <view class="printer-footer">
          <button class="search-btn" @click="searchPrint">
            <text>搜索蓝牙设备</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 添加/编辑飞蛾打印机对话框 -->
    <view v-if="showFeiyeDialog" class="feiye-modal" @click.self="showFeiyeDialog = false">
      <view class="feiye-modal-content" @click.stop>
        <view class="feiye-header">
          <text class="feiye-title">
            {{ feiyeForm.id ? '编辑' : '添加' }}飞蛾打印机
          </text>
          <text class="feiye-close" @click="showFeiyeDialog = false">
            ✕
          </text>
        </view>
        <view class="feiye-body">
          <view class="form-item">
            <view class="label-box">
              <text class="required">
                *
              </text>
              <text class="form-label">
                打印机名称
              </text>
            </view>
            <input
              v-model="feiyeForm.name"
              class="form-input"
              placeholder="请输入打印机名称"
            >
          </view>
          <view class="form-item">
            <view class="label-box">
              <text class="required">
                *
              </text>
              <text class="form-label">
                打印机编号
              </text>
            </view>
            <input
              v-model="feiyeForm.num"
              class="form-input"
              placeholder="请输入打印机编号"
            >
          </view>
          <view class="form-item">
            <view class="label-box">
              <text class="required">
                *
              </text>
              <text class="form-label">
                打印机Key
              </text>
            </view>
            <input
              v-model="feiyeForm.key"
              class="form-input"
              placeholder="请输入打印机Key"
            >
          </view>
          <view class="form-item">
            <view class="label-box">
              <text class="form-label">
                备注
              </text>
            </view>
            <input
              v-model="feiyeForm.note"
              class="form-input"
              placeholder="请输入备注信息"
            >
          </view>
        </view>
        <view class="feiye-footer">
          <button class="btn-cancel" @click="showFeiyeDialog = false">
            取消
          </button>
          <button class="btn-confirm" @click="saveFeiyePrinter">
            确定
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import PrintPreview from '@/components/PrintPreview.vue';
import S1Header from '@/components/S1Header.vue';
import { post } from '@/utils/request';

// 声明 Android 桥接类型
declare global {
  interface Window {
    Android?: {
      dDisconnectDevice: (id: string) => void;
      dConnectUsbDevices: (id: string) => void;
      dConnectBlueToothDevice: (address: string) => void;
      dIsDeviceConnected: () => boolean;
      dConnectedDeviceName: () => string;
      dConnectedDeviceId: () => string;
      dGetPairedBluetoothDeviceList: () => string;
      dGetUsbDeviceList: () => string;
      dStartBluetoothScan: (duration: number) => void;
      dGetScanResult: () => string;
    };
  }
}

interface FormData {
  printer: string;
  count: number;
  print_huozhu_chaifen: number;
  print_fenjian: number;
  isAoto: number;
  use_print_template: number;
  printer_type: number; // 0=斯普瑞特 1=飞蛾
  fei_id: string; // 飞蛾打印机ID
}

defineOptions({ name: 'DefaultConfig' });

const formData = ref<FormData>({
  printer: '',
  count: 1,
  print_huozhu_chaifen: 1,
  print_fenjian: 0,
  isAoto: 1,
  use_print_template: 1,
  printer_type: 0,
  fei_id: '',
});

// 打印内容配置
const header = ref({
  mark: '头部信息',
  boxList: [
    { flield_name: '订单状态', field_name: 'order_status', checked: false },
    { flield_name: '票号', field_name: 'piao_num', checked: true },
    { flield_name: '操作员', field_name: 'cashier_id', checked: true },
    { flield_name: '交易中心', field_name: 'deal_address', checked: true },
    { flield_name: '销售凭证', field_name: 'voucher', checked: true },
    { flield_name: '买家', field_name: 'maijia', checked: true },
  ],
});

const goods = ref({
  mark: '商品信息',
  boxList: [
    { flield_name: '品名', field_name: 'goods_name', checked: true },
    { flield_name: '货主批次', field_name: 'huozhupici', checked: true },
    { flield_name: '数量', field_name: 'goods_shuliang', checked: true },
    { flield_name: '单价', field_name: 'goods_danjia', checked: true },
    { flield_name: '货款', field_name: 'goods_jiage', checked: true },
    { flield_name: '小计', field_name: 'goods_total', checked: true },
    { flield_name: '总件数', field_name: 'goods_num', checked: true },
  ],
});

const settle = ref({
  mark: '结算信息',
  boxList: [
    { flield_name: '总金额', field_name: 'zongjine', checked: true },
    { flield_name: '备注', field_name: 'notes', checked: true },
    { flield_name: '赊欠', field_name: 'sheqian', checked: true },
    { flield_name: '开单时间', field_name: 'add_time', checked: true },
    { flield_name: '打印时间', field_name: 'print_time', checked: true },
  ],
});

const other = ref({
  mark: '其他信息',
  boxList: [
    { flield_name: '档口电话', field_name: 'mobile', checked: true },
    { flield_name: '档口地址', field_name: 'address', checked: true },
    { flield_name: '支付二维码', field_name: 'pay_qr_code', checked: false },
  ],
});

const goBack = () => {
  uni.navigateBack();
};

// 防抖保存定时器
let saveTimer: any = null;

// 防抖保存函数 - 用户停止操作1秒后才保存
const debounceSave = () => {
  if (saveTimer) {
    clearTimeout(saveTimer);
  }
  saveTimer = setTimeout(() => {
    saveConfig();
  }, 1000); // 1秒后保存
};

// 从服务器获取打印配置
const getPrintConfig = async () => {
  try {
    const res: any = await post('/syapi/config/receiptField', { data: {} });

    if (res.code === 200) {
      const data = res.data;

      // 更新表单数据
      formData.value = {
        printer: data.printer_name || '',
        count: Number(data.printer_number) || 1,
        print_huozhu_chaifen: Number(data.print_huozhu_chaifen) || 1,
        print_fenjian: Number(data.print_fenjian) || 0,
        isAoto: Number(data.is_auto_receipt) || 1,
        use_print_template: Number(data.use_print_template) || 1,
        printer_type: Number(data.printer_type) || 0,
        fei_id: data.fei_id || '',
      };

      // 更新打印内容配置
      if (data.field) {
        // 头部信息
        if (data.field.header && Array.isArray(data.field.header)) {
          data.field.header.forEach((item: any) => {
            const field = header.value.boxList.find(f => f.field_name === item.field_name);
            if (field) {
              field.checked = item.checked || false;
            }
          });
        }

        // 商品信息
        if (data.field.goods && Array.isArray(data.field.goods)) {
          data.field.goods.forEach((item: any) => {
            const field = goods.value.boxList.find(f => f.field_name === item.field_name);
            if (field) {
              field.checked = item.checked || false;
            }
          });
        }

        // 结算信息
        if (data.field.settle && Array.isArray(data.field.settle)) {
          data.field.settle.forEach((item: any) => {
            const field = settle.value.boxList.find(f => f.field_name === item.field_name);
            if (field) {
              field.checked = item.checked || false;
            }
          });
        }

        // 其他信息
        if (data.field.other && Array.isArray(data.field.other)) {
          data.field.other.forEach((item: any) => {
            const field = other.value.boxList.find(f => f.field_name === item.field_name);
            if (field) {
              field.checked = item.checked || false;
            }
          });
        }
      }

      // 保存到本地存储
      uni.setStorageSync('printer_info', JSON.stringify(data));
      uni.setStorageSync('printer_type', data.printer_type || 0);

      console.log('获取打印配置成功:', formData.value);
    }
    else {
      console.error('获取打印配置失败:', res.msg);
    }
  }
  catch (error) {
    console.error('获取打印配置异常:', error);
  }
};

// 保存配置
const saveConfig = async () => {
  try {
    // 构建content数据 - 与PC端完全一致的格式
    // 先添加打印机配置项
    let data = [
      {
        field_name: 'printer_number',
        flield_name: '默认打印份数',
        value: formData.value.count,
      },
      {
        field_name: 'printer_name',
        flield_name: '打印机名称',
        value: formData.value.printer,
      },
      {
        field_name: 'printer_spec',
        flield_name: '小票规格',
        value: '80mm',
      },
      {
        field_name: 'is_auto_receipt',
        flield_name: '自动打印',
        value: formData.value.isAoto == 1 ? 1 : 0,
      },
    ];

    // 再添加所有复选框数据
    data = [
      ...data,
      ...goods.value.boxList,
      ...header.value.boxList,
      ...other.value.boxList,
      ...settle.value.boxList,
    ];

    // 与PC端完全一致的参数结构
    const params = {
      printer_spec: '80mm',
      is_auto_receipt: formData.value.isAoto == 1 ? '1' : '0',
      printer_name: formData.value.printer,
      printer_number: formData.value.count,
      printer_type: formData.value.printer_type || 0,
      print_huozhu_chaifen: formData.value.print_huozhu_chaifen,
      print_fenjian: formData.value.print_fenjian,
      fujiafei: 0,
      use_print_template: formData.value.use_print_template,
      speaker: 0,
      fei_id: formData.value.fei_id || '',
      content: data,
    };

    console.log('保存配置参数:', params);
    const res: any = await post('/syapi/config/receiptsave', { data: params });

    if (res.code === 200) {
      // 重新获取最新配置
      await getPrintConfig();
      uni.showToast({
        title: '保存成功',
        icon: 'success',
      });
    }
    else {
      uni.showToast({
        title: res.msg || '保存失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('保存失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'none',
    });
  }
};

// 打印机相关状态
const selectPrinterShow = ref(false);
const searchLoading = ref(false);
const elementLoadingText = ref('');
const blueDevice = ref([]);
const usbDevice = ref([]);
const printerList = ref([]);
const connectDeviceId = ref('');
const disconnect = ref(false);

// 打印预览相关
const printPreviewVisible = ref(false);
const previewContent = ref('');
const userinfo = ref(null);

// 打印测试数据
const printDetails = ref({
  sellerInfo: '',
  piao_num: '009',
  transactionCenter: '',
  storeReceipt: '',
  maijia: '临时打单',
  sheqian: 100,
  creditDate: '2024-12-20 15:20',
  total_price: '88',
  notes: '备注信息',
  user: {
    name: '系统操作员',
  },
  order_detail: [
    {
      name: '海南大香蕉',
      huozhupici: '(张三-999)',
      add_time: '2024-12-20 15:20',
      goods_price: 88,
      weight: '1',
      unit: '公斤',
      num: '1',
      price: '1',
      order_detail_fujiafei: '测试',
      order_detail_pici: {
        huozhu_name: '张三',
        huozhu: {
          name: '张三',
        },
        pici: '11',
      },
      details: {
        quantity: 1,
        weight: 1,
        unitPrice: '8',
        packageingFee: '--',
      },
      expenses: {
        laborFee: 14,
        paymentAmount: 162,
      },
    },
  ],
  summary: {
    totalQuantity: 2,
    totalAmount: 88,
    amountOwed: 88,
  },
  qrCodeImage: '',
  staffInfo: {
    operator: '',
    cashier: '',
    salesManager: '',
  },
  disclaimer:
    '以上食用农产品均履行进货检查法定程序索证索票齐全销售者特此声明。',
});

// 飞蛾打印机表单
const showFeiyeDialog = ref(false);
const feiyeForm = ref({
  id: null as number | null,
  name: '',
  num: '',
  key: '',
  note: '',
});

// 检测是否为 Android 环境
const isAndroidEnv = () => {
  try {
    const nav = typeof navigator !== 'undefined' ? navigator : undefined;
    const w = typeof window !== 'undefined' ? window : undefined;
    const uaIsAndroid = !!(nav && /Android/i.test(nav.userAgent));
    const hasBridge = !!(w && w.Android);
    return uaIsAndroid || hasBridge;
  }
  catch (e) {
    return false;
  }
};

// 断开打印机连接
const disconnectPrint = () => {
  if (!isAndroidEnv() || !window.Android) return;
  window.Android.dDisconnectDevice('123');
  disconnect.value = false;
  connectDeviceId.value = '';
  formData.value.printer = '';
};

// 连接斯普瑞特蓝牙/USB打印机
const selectlyPrint = (item: any, type: number) => {
  if (!isAndroidEnv() || !window.Android) {
    uni.showToast({ title: '当前环境不支持', icon: 'none' });
    return;
  }

  // 先断开已有连接
  window.Android.dDisconnectDevice('123');

  // 根据类型连接: 1=USB, 2=蓝牙
  if (type === 1) {
    window.Android.dConnectUsbDevices(item.id);
  }
  else {
    window.Android.dConnectBlueToothDevice(item.address);
  }

  searchLoading.value = true;
  elementLoadingText.value = '打印机连接中.........';

  setTimeout(() => {
    searchLoading.value = false;
    const connectResult = window.Android.dIsDeviceConnected();

    if (!connectResult) {
      uni.showToast({ title: '打印机未连接成功', icon: 'error' });
      disconnect.value = false;
      formData.value.printer = '';
    }
    else {
      uni.showToast({ title: '打印机连接成功', icon: 'success' });
      formData.value.printer = type === 1 ? item.deviceName : item.name;
      formData.value.printer_type = 0; // 斯普瑞特打印机
      formData.value.fei_id = ''; // 清空飞蛾打印机ID

      // 更新本地 userInfo
      try {
        const userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}');
        if (!userInfo.print) userInfo.print = {};
        userInfo.print.use_printer_id = item.address || item.id;
        userInfo.print.use_printer_name = formData.value.printer;
        uni.setStorageSync('userInfo', JSON.stringify(userInfo));
      }
      catch (e) {
        console.error('更新 userInfo 失败:', e);
      }

      selectPrinterShow.value = false;
      saveConfig();
    }
  }, 2000);
};

// 选择飞蛾打印机
const selectFeiyePrint = async (item: any) => {
  console.log('选择飞蛾打印机:', item);

  // 如果之前连接了本地打印机，断开
  if (disconnect.value) {
    disconnectPrint();
  }

  formData.value.printer = item.name;
  formData.value.printer_type = 1; // 飞蛾打印机
  formData.value.fei_id = item.id;

  selectPrinterShow.value = false;

  // 调用接口保存打印机配置
  try {
    uni.showLoading({ title: '保存中...', mask: true });

    const res: any = await post('/syapi/config/receiptsave', {
      data: {
        printer_name: item.name,
        printer_type: 1, // 飞蛾打印机
        fei_id: item.id,
      },
    });

    uni.hideLoading();

    if (res.code === 200) {
      // 保存成功后再调用 saveConfig
      saveConfig();
      uni.showToast({ title: `已选择：${item.name}`, icon: 'success' });
    }
    else {
      uni.showToast({ title: res.msg || '保存失败', icon: 'none' });
    }
  }
  catch (e) {
    uni.hideLoading();
    console.error('保存打印机配置失败:', e);
    uni.showToast({ title: '保存失败，请重试', icon: 'none' });
  }
};

// 搜索蓝牙打印机
const searchPrint = () => {
  if (!isAndroidEnv() || !window.Android) {
    uni.showToast({ title: '当前环境不支持', icon: 'none' });
    return;
  }

  window.Android.dStartBluetoothScan(3);
  searchLoading.value = true;
  elementLoadingText.value = '打印机搜索中.........';

  setTimeout(() => {
    searchLoading.value = false;
    const res = window.Android.dGetScanResult();
    const devices = JSON.parse(res || '[]');

    // 过滤出斯普瑞特打印机
    const aliases = ['POS891/892 Printer', 'test'];
    blueDevice.value = devices.filter(
      (it: any) => it && it.name && aliases.includes(it.name),
    );
  }, 4000);
};

// 获取打印机列表
const getPrinterList = async () => {
  selectPrinterShow.value = true;

  // 获取飞蛾打印机列表
  try {
    const res: any = await post('/syapi/dayin/get_print_list', { data: {} });
    if (res.code === 200) {
      printerList.value = res.data || [];
    }
  }
  catch (e) {
    console.error('获取飞蛾打印机列表失败:', e);
  }

  // Android 环境获取蓝牙和 USB 打印机
  if (isAndroidEnv() && window.Android) {
    try {
      const blueRes = window.Android.dGetPairedBluetoothDeviceList();
      const usbRes = window.Android.dGetUsbDeviceList();

      if (blueRes && blueRes !== 'undefied') {
        const devices = JSON.parse(blueRes);
        const aliases = ['POS891/892 Printer', 'test'];
        blueDevice.value = devices.filter(
          (it: any) => it && it.name && aliases.includes(it.name),
        );
      }

      if (usbRes) {
        usbDevice.value = JSON.parse(usbRes);
      }

      // 获取当前连接状态
      disconnect.value = window.Android.dIsDeviceConnected();
      if (disconnect.value) {
        formData.value.printer = window.Android.dConnectedDeviceName();
        connectDeviceId.value = window.Android.dConnectedDeviceId();
      }
    }
    catch (e) {
      console.error('获取 Android 打印机失败:', e);
    }
  }
};

// 添加飞蛾打印机
const addFeiyePrinter = () => {
  feiyeForm.value = {
    id: null,
    name: '',
    num: '',
    key: '',
    note: '',
  };
  showFeiyeDialog.value = true;
};

// 编辑飞蛾打印机
const editFeiyePrinter = (item: any) => {
  feiyeForm.value = {
    id: item.id,
    name: item.name,
    num: item.num,
    key: item.key,
    note: item.note || '',
  };
  showFeiyeDialog.value = true;
};

// 保存飞蛾打印机
const saveFeiyePrinter = async () => {
  // 表单验证
  if (!feiyeForm.value.name) {
    uni.showToast({ title: '请输入打印机名称', icon: 'none' });
    return;
  }
  if (!feiyeForm.value.num) {
    uni.showToast({ title: '请输入打印机编号', icon: 'none' });
    return;
  }
  if (!feiyeForm.value.key) {
    uni.showToast({ title: '请输入打印机Key', icon: 'none' });
    return;
  }

  try {
    const result: any = await post('/syapi/dayin/addfeie', { data: feiyeForm.value });
    if (result.code === 200) {
      uni.showToast({ title: '保存成功', icon: 'success' });
      printerList.value = result.data || [];
      showFeiyeDialog.value = false;
    }
    else {
      uni.showToast({ title: result.msg || '保存失败', icon: 'error' });
    }
  }
  catch (e) {
    console.error('保存飞蛾打印机失败:', e);
    uni.showToast({ title: '保存失败', icon: 'error' });
  }
};

// 删除飞蛾打印机
const deleteFeiyePrinter = async (id: number) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该打印机吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result: any = await post('/syapi/dayin/del_print', { data: { id } });
          if (result.code === 200) {
            uni.showToast({ title: '删除成功', icon: 'success' });
            printerList.value = result.data || [];
          }
          else {
            uni.showToast({ title: result.msg || '删除失败', icon: 'error' });
          }
        }
        catch (e) {
          console.error('删除飞蛾打印机失败:', e);
          uni.showToast({ title: '删除失败', icon: 'error' });
        }
      }
    },
  });
};

// 选择打印机
const selectPrinter = () => {
  getPrinterList();
};

// 默认打印份数变化
const onCountChange = (e: any) => {
  const newValue = e.value || e;
  formData.value.count = newValue;
  console.log('默认打印份数变化:', formData.value.count);
  debounceSave();
};

// 开单打印模式变化
const onPrintModeChange = (e: any) => {
  formData.value.print_huozhu_chaifen = Number(e.detail.value);
  console.log('开单打印模式变化:', formData.value.print_huozhu_chaifen);
  debounceSave();
};

// 分拣单打印模式变化
const onSortModeChange = (e: any) => {
  formData.value.print_fenjian = Number(e.detail.value);
  console.log('分拣单打印模式变化:', formData.value.print_fenjian);
  debounceSave();
};

// 结账自动打印变化
const onAutoPrintChange = (e: any) => {
  formData.value.isAoto = e.detail.value ? 1 : 0;
  console.log('结账自动打印变化:', formData.value.isAoto, 'e.detail.value:', e.detail.value);
  debounceSave();
};

// 小票打印样式变化
const onTemplateChange = (e: any) => {
  formData.value.use_print_template = Number(e.detail.value);
  console.log('小票打印样式变化:', formData.value.use_print_template);
  debounceSave();
};

// 打印内容复选框切换
const toggleCheck = (category: string, index: number) => {
  if (category === 'header') {
    header.value.boxList[index].checked = !header.value.boxList[index].checked;
  }
  else if (category === 'goods') {
    goods.value.boxList[index].checked = !goods.value.boxList[index].checked;
  }
  else if (category === 'settle') {
    settle.value.boxList[index].checked = !settle.value.boxList[index].checked;
  }
  else if (category === 'other') {
    other.value.boxList[index].checked = !other.value.boxList[index].checked;
  }

  console.log('打印内容变化:', category, index);
  saveConfig(); // 复选框变化立即保存
};

onMounted(() => {
  getPrintConfig();

  // 初始化用户信息
  try {
    const userInfoStr = uni.getStorageSync('userInfo');
    if (userInfoStr) {
      userinfo.value = JSON.parse(userInfoStr);
      printDetails.value.transactionCenter = userinfo.value?.area || '';
      printDetails.value.storeReceipt = userinfo.value?.dangkou_name || '';
      printDetails.value.sellerInfo = userinfo.value?.name || '';
      printDetails.value.staffInfo.operator = userinfo.value?.name || '';
      printDetails.value.staffInfo.cashier = userinfo.value?.name || '';
      printDetails.value.staffInfo.salesManager = userinfo.value?.name || '';
    }
  }
  catch (e) {
    console.error('初始化用户信息失败:', e);
  }

  // 初始化打印机连接状态
  if (isAndroidEnv() && window.Android) {
    try {
      disconnect.value = window.Android.dIsDeviceConnected();
      if (disconnect.value) {
        formData.value.printer = window.Android.dConnectedDeviceName();
        connectDeviceId.value = window.Android.dConnectedDeviceId();
      }
      else {
        formData.value.printer = '';
        connectDeviceId.value = '';
      }
    }
    catch (e) {
      console.error('初始化打印机状态失败:', e);
    }
  }
});
</script>

<style scoped lang="scss">
.page-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx; /* 为底部固定的打印预览留出空间 */
}

/* 固定头部样式 */
.header-fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #fff;
}

.content-wrapper {
  padding: 20rpx 32rpx;
  margin-top: 170rpx; /* S1Header高度: h-90rpx + pt-80rpx = 170rpx */
}

/* 打印预览固定在底部 */
.print-preview-fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1rpx solid #e0e0e0;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.08);
  z-index: 100;
}

.form-list {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);

  &:last-child {
    border-bottom: none;
  }

  &.column {
    flex-direction: column;
    align-items: flex-start;
  }
}

.item-label {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.item-right {
  display: flex;
  align-items: center;
}

.item-value {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.arrow-icon {
  width: 16rpx;
  height: 28rpx;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20rpx;
}

.radio-label {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
  margin-bottom: 20rpx;
}

.radio-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #666;
}

// 选择打印内容区域样式（朴素版）
.print-content-section {
  padding: 30rpx 40rpx !important; /* 与上方form-item一致 */
  background-color: #fff !important; /* 强制与上方保持白底 */
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.06); /* 与其他form-item分隔线一致 */

  .item-label {
    font-size: 30rpx;
    color: #333;
    font-weight: 500;
    margin-bottom: 20rpx; /* 标题与内容间距 */
  }
}

.content-group {
  background-color: #fff !important; /* 分组白底 */
  padding: 24rpx 40rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);

  &:last-child {
    border-bottom: none;
  }
}

.group-title-wrapper {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.group-title {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

/* 自适应宽度，自动换行 */
.checkbox-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.checkbox-label {
  display: inline-flex;
  align-items: center;
  padding: 10rpx 16rpx;
  background-color: #fff;
  border: 1rpx solid #dcdfe6;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.checkbox-text {
  margin-left: 8rpx;
  font-size: 26rpx;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.checkbox-text.checked {
  color: #4ca75b;
}

// 打印机选择对话框样式
.printer-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.printer-modal-content {
  width: 90%;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.printer-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  background-color: #fff;
}

.header-title {
  flex: 1;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.add-feie-btn {
  background-color: #4ca75b;
  color: #fff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.close-icon {
  font-size: 40rpx;
  color: #d81e06;
  cursor: pointer;
  font-weight: bold;
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
  font-size: 28rpx;
}

.loading-icon {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #fff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: rotate 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.printer-list {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
  min-height: 400rpx;
  max-height: 60vh;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  color: #999;
  font-size: 28rpx;
  text-align: center;
}

.sub-tip {
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #ccc;
}

.printer-item {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 30rpx;
  margin-bottom: 20rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  border: 1rpx solid #dcdfe6;
}

.printer-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.label {
  font-size: 26rpx;
  color: #909399;
}

.value {
  font-size: 28rpx;
  color: #303133;
  margin-left: 12rpx;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.value.bold {
  font-weight: 600;
  border: none;
  padding: 0;
  font-size: 30rpx;
}

.printer-note {
  font-size: 24rpx;
  color: #606266;
  font-weight: 500;
}

.note-text {
  color: #aac7ef;
  font-weight: normal;
}

.printer-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
  margin-left: 20rpx;
}

.action-btn {
  width: 68rpx;
  height: 68rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
  cursor: pointer;
}

.edit-btn {
  background-color: #ecf5ff;
}

.delete-btn {
  background-color: #fef0f0;
}

.action-btn:active {
  transform: scale(0.92);
  opacity: 0.7;
}

.action-text {
  font-size: 36rpx;
}

.action-icon {
  width: 36rpx;
  height: 36rpx;
}

/* CSS绘制编辑图标 */
.icon-edit {
  width: 32rpx;
  height: 32rpx;
  position: relative;
}

.icon-edit::before {
  content: '';
  position: absolute;
  width: 20rpx;
  height: 3rpx;
  background: #409EFF;
  transform: rotate(-45deg);
  left: 6rpx;
  top: 14rpx;
}

.icon-edit::after {
  content: '';
  position: absolute;
  width: 8rpx;
  height: 8rpx;
  border: 3rpx solid #409EFF;
  border-left: none;
  border-bottom: none;
  transform: rotate(-45deg);
  right: 6rpx;
  top: 4rpx;
}

/* CSS绘制删除图标 */
.icon-delete {
  width: 32rpx;
  height: 32rpx;
  position: relative;
}

.icon-delete::before {
  content: '';
  position: absolute;
  width: 20rpx;
  height: 22rpx;
  border: 3rpx solid #F56C6C;
  border-top: none;
  border-radius: 0 0 4rpx 4rpx;
  left: 6rpx;
  top: 10rpx;
}

.icon-delete::after {
  content: '';
  position: absolute;
  width: 26rpx;
  height: 3rpx;
  background: #F56C6C;
  left: 3rpx;
  top: 8rpx;
  border-radius: 2rpx;
}

.printer-footer {
  padding: 24rpx 30rpx;
  border-top: 1rpx solid #eee;
  background-color: #fff;
}

.search-btn {
  width: 100%;
  height: 80rpx;
  background-color: #4ca75b;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  box-shadow: 0 2rpx 8rpx rgba(76, 167, 91, 0.2);
}

.search-icon {
  font-size: 32rpx;
}

// 飞蛾打印机对话框样式
.feiye-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1002;
  display: flex;
  align-items: center;
  justify-content: center;
}

.feiye-modal-content {
  width: 85%;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.feiye-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.feiye-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.feiye-close {
  font-size: 40rpx;
  color: #999;
}

.feiye-body {
  max-height: 60vh;
  overflow-y: auto;

  .form-item {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    width: 87%;
  }
}

.label-box {
  display: flex;
  align-items: center;
  margin-bottom: 6rpx;
}

.required {
  color: #ff4d4f;
  margin-right: 5rpx;
  font-size: 28rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
}

.form-input {
  width: 100%;
  height: 70rpx;
  background-color: #f5f5f5;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.feiye-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.btn-cancel,
.btn-confirm {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  font-size: 30rpx;
  border: none;
}

.btn-cancel {
  background-color: #f5f5f5;
  color: #666;
}

.btn-confirm {
  background-color: #4ca75b;
  color: #fff;
}

// 打印预览弹窗样式（用于实际打印流程）
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-modal-content {
  width: 335px;
  max-height: 85vh;
  background-color: #fff;
  border-radius: 8rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.preview-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.preview-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.preview-close {
  font-size: 40rpx;
  color: #999;
  font-weight: bold;
}

.preview-body {
  flex: 1;
  overflow-y: auto;
  max-height: 60vh;
  background-color: #fff;
}

.preview-content {
  padding: 0;
  background-color: #fff;
  font-size: 12px;
  color: #000;
  box-sizing: border-box;
}

.preview-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
  background-color: #fff;
}

// 打印内容选择样式
.content-group {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
}

.group-title {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
}

.checkbox-wrapper {
  display: flex;
  flex-wrap: wrap;
}

.checkbox-label {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.checkbox-text {
  margin-left: 10rpx;
  font-size: 26rpx;
  color: #666;
}
</style>
